//
//  RxTableViewDataManager.swift
//  Swift-Example
//
//  Created by apang on 2018/8/9.
//  Copyright © 2018 apang.men All rights reserved.
//

import Foundation
import RxCocoa
import RxSwift
import RxDataSources

class RxTableViewDataManager: NSObject {
    var originData:[ProvinceModel] = []
    var sections : BehaviorRelay<[ProvinceModel]>?
    override init() {
        super.init()
        let filePath = Bundle.main.path(forResource: "Resource/json/quHuaDaiMa", ofType: "json")
        let jsonStr = try! String.init(contentsOfFile: filePath!)
        let data = jsonStr.data(using: String.Encoding.utf8)
        let decoder = JSONDecoder()
        originData = try! decoder.decode([ProvinceModel].self, from: data!)
        var tmpArr:[ProvinceModel] = []
        for element in originData {
            var tmp = element
            if (tmp.isSelect == false){
                tmp.children.removeAll()
            }
            tmpArr.append(tmp)
        }
        sections = BehaviorRelay<[ProvinceModel]>(value: tmpArr)
    }
}
extension RxTableViewDataManager: ExRxTableViewHeaderDelegate {
    func closeSection(open: Bool, section: NSInteger) {
        var tmpArr = sections?.value
        var oldModel = tmpArr![section]
        let originModel = originData[section]
        if (open == true) {
            //恢复children
            oldModel.children = originModel.children
        }else{
            //删除
            oldModel.children.removeAll()
        }
        oldModel.select = open
        let str:String = open ? "展开列表" : "关闭列表"
        print(str,open,oldModel.children.count)
        tmpArr![section] = oldModel
        sections?.accept(tmpArr!)
    }
}
